package cn.wolfcode.web.interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.JsonResult;
import cn.wolfcode.mapper.PermissionMapper;
import cn.wolfcode.util.RequiredPermission;
import cn.wolfcode.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.security.interfaces.RSAKey;
import java.util.List;

public class PermissionInterceptor implements HandlerInterceptor {
    @Autowired
    private PermissionMapper permissionMapper ;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {
        Employee employee = UserContext.getCurrentUser();
        if(employee.isAdmin()){
            return true;
        }
        //如果不是管理员,获取当前要执行的控制器的处理方法
        HandlerMethod handlerMethod = (HandlerMethod) handler ;

        RequiredPermission annotation = handlerMethod.getMethodAnnotation(RequiredPermission.class);
        if(annotation == null){
            return true ;
        }
        String expression = annotation.expression();
        List<String> list = UserContext.getExpression();
        System.out.println(list);
        if(list.contains(expression)){
            return true ;
        }
        if(!handlerMethod.hasMethodAnnotation(ResponseBody.class)){
            request.getRequestDispatcher("/WEB-INF/views/common/nopermission.ftl").forward(request,response );
        }else{
            JsonResult json = new JsonResult(false,"您没有权限操作" );
            response.getWriter().print(json);
        }

        return false;
    }
}
